import template from "../template";
import { unit, A4 } from "../utils/config";
import { computeString } from "../utils";

export default function (options, callback, computePages) {
  // 创建iframe标签
  const $iframe = document.createElement("iframe");
  $iframe.setAttribute("id", "browser-table-print");
  // 一页内容
  const size = {
    width: options.width || A4.width + unit,
    height: options.height || A4.height + unit,
    padding: options.padding || "0 10px",
  };
  // 测试预览
  $iframe.setAttribute(
    "style",
    `width:${size.width};height:${size.height};visibility:hidden;position:absolute;`
  );
  // iframe标签渲染完毕
  $iframe.onload = function () {
    const page = template.page
      .replace(
        "#width#",
        computeString(size.width, (value) => value - options.overflowWidth)
      )
      .replace(
        "#height#",
        computeString(size.height, (value) => value - options.overflowHeight)
      )
      .replace("#padding#", size.padding);
    // 添加自定义样式
    const style = template.style
      .replace("#size#", `${size.width} ${size.height}`)
      .replace("##", options.style || "");
    options.sizeStyle = style;
    // 根据内容计算所需页数
    options.$iframe = $iframe;
    computePages(page, options, (pages) => {
      // 添加html容器
      const html = template.html
        .replace("##", style + pages.reduce((t, i) => t + i.content, ""))
        .replace(
          "#htmlPrintCss#",
          `<link rel="stylesheet" href="${
            options.htmlPrintCss || "browser-table-print.css"
          }" />`
        );
      // 大小重置为0
      $iframe.setAttribute(
        "style",
        "visibility:hidden;height:0;width:0;position:absolute;"
      );
      // 渲染内容到页面
      $iframe.contentDocument.write(html);
      // 获取css
      const link = $iframe.contentDocument.querySelectorAll("link")[0];
      // 等待css加载完成
      link.onload = () => {
        // 回调
        callback &&
          callback({
            // 打印方法
            print() {
              setTimeout(() => {
                $iframe.contentWindow.print();
                $iframe.parentElement.removeChild($iframe);
              }, 300);
            },
            // 获取iframe
            getIframe() {
              return $iframe;
            },
          });
      };
    });
  };

  // 渲染iframe
  document.body.appendChild($iframe);
}
